import {
  Button,
  Card,
  message,
  Space,
  Table,
  TablePaginationConfig,
  Tag,
} from 'antd';
import SearchRole from './Search';
import RoleDialog from './Dialog';
import { useState, useEffect } from 'react';
import { RoleData, SearchRoleQuery } from '@/types/sys';
import { pageation as paginationInterface } from '@/types/global';
import { getRoleList, removeRole } from '@/api/sys';
import dayjs from 'dayjs';

// 提取ActionButtons组件
interface TableActionProps {
  record: RoleData;
  onEdit: (record: RoleData) => void;
  onDelete: (record: RoleData) => void;
}

const TableActions = ({ record, onEdit, onDelete }: TableActionProps) => (
  <Space>
    <Button type="primary" onClick={() => onEdit(record)}>
      编辑
    </Button>
    <Button type="primary" danger onClick={() => onDelete(record)}>
      删除
    </Button>
  </Space>
);

function Role() {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('新增角色');
  const [pageation, setPagination] = useState<paginationInterface>({
    page: 1,
    pageSize: 10,
  });

  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState(false);
  const [record, setRecord] = useState<RoleData | null>(null);
  const [data, setData] = useState<RoleData[]>([]);

  // 表格列定义
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'role_name',
      key: 'role_name',
      align: 'center' as const,
    },
    {
      title: '角色描述',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center' as const,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center' as const,
      render: (_: unknown, record: RoleData) => (
        <>
          {record.status == '1' ? (
            <Tag color="success">启用</Tag>
          ) : (
            <Tag color="error">禁用</Tag>
          )}
        </>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      align: 'center' as const,
      render(_: unknown, record: RoleData) {
        return <>{dayjs(record.create_time).format('YYYY-MM-DD HH:mm:ss')}</>;
      },
    },

    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'update_time',
      align: 'center' as const,
      render: (_: unknown, record: RoleData) => (
        <>{dayjs(record.update_time).format('YYYY-MM-DD HH:mm:ss')}</>
      ),
    },

    {
      title: '操作',
      key: 'operation',
      align: 'center' as const,
      render: (_: unknown, record: RoleData) => (
        <TableActions
          record={record}
          onEdit={() => handleEdit(record)}
          onDelete={() => handleDelete(record)}
        />
      ),
    },
  ];

  const fetchData = useCallback(
    async (params: SearchRoleQuery = {}) => {
      try {
        setLoading(true);
        const query = { ...params, ...pageation };
        const result = await getRoleList(query);

        if (result?.data) {
          const { data, total } = result.data;
          setData(data || []);
          setTotal(total || 0);
        }
      } catch (error) {
        console.error('获取角色列表失败:', error);
      } finally {
        setLoading(false);
      }
    },
    [pageation]
  );
  // 搜索处理函数

  const handleSearch = useCallback(
    (values: SearchRoleQuery) => {
      fetchData(values);
    },
    [fetchData]
  );
  const handleTableChange = useCallback((pagination: TablePaginationConfig) => {
    setPagination({
      page: pagination.current || 1,
      pageSize: pagination.pageSize || 10,
    });
  }, []);
  // 编辑处理函数
  const handleEdit = (row: RoleData) => {
    try {
      setRecord(row);
      setTitle('编辑角色');
      setOpen(true);
      console.log('edit', row);
    } catch (error) {
      console.error('编辑处理出错:', error);
    }
  };

  // 删除处理函数
  const handleDelete = async (row: RoleData) => {
    console.log('delete', row, typeof row.id);
    try {
      if (!row.id) return;
      const result = await removeRole(row.id);
      console.log('delete', row);
      if (!result) {
        console.error('删除角色失败');
        return;
      }
      // 删除成功后，刷新数据
      message.success('删除成功');
      // 实现删除逻辑，并确保在删除后刷新数据
      fetchData({});
    } catch (error) {
      console.error('删除处理出错:', error);
    }
  };

  // 新增处理函数
  const handleAdd = () => {
    setRecord(null);
    setTitle('新增角色');
    setOpen(true);
  };
  useEffect(() => {
    fetchData();
  }, [fetchData]);
  return (
    <>
      <Card className="mb-2">
        <SearchRole onFinish={handleSearch} onAdd={handleAdd} />
      </Card>
      <Table
        loading={loading}
        bordered
        scroll={{
          x: 'max-content',
          y: 'calc(100vh - 320px)',
        }}
        dataSource={data}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize: pageation.pageSize,
          total: total,
          current: pageation.page,
          pageSizeOptions: [10, 20, 50, 100],
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        onChange={handleTableChange}
      />
      <RoleDialog
        title={title}
        open={open}
        setOpen={setOpen}
        record={record}
        onSuccess={fetchData}
      />
    </>
  );
}

export default Role;
